package com.flower.controller.admin;

import com.flower.domain.dto.buyer.PageBuyerDto;
import com.flower.domain.dto.buyer.farmer.PageFarmerDto;
import com.flower.domain.entity.Buyer;
import com.flower.domain.entity.Farmer;
import com.flower.service.BuyerService;
import com.flower.service.FarmerService;
import com.flower.utils.AjaxResult;
import com.flower.utils.Md5Util;
import com.flower.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 管理端用户管理
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private FarmerService farmerService;

    @Autowired
    private BuyerService buyerService;

    /**
     * 获取花农列表
     * @param keyword
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @GetMapping("/getFarmerList")
    public AjaxResult getFarmerList(@RequestParam(required = false) String keyword,
                                   @RequestParam(defaultValue = "1") Integer pageNumber,
                                   @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询花农列表，参数：keyword={}, pageNumber={}, pageSize={}", keyword, pageNumber, pageSize);
        PageFarmerDto pageFarmerDto = new PageFarmerDto();
        pageFarmerDto.setPageNumber(pageNumber);
        pageFarmerDto.setPageSize(pageSize);
        pageFarmerDto.setKeyword(keyword);
        return AjaxResult.success("查询成功", farmerService.pageList(pageFarmerDto));
    }

    /**
     * 新增花农信息
     * @param farmer
     * @return
     */
    @Log(name = "新增花农")
    @PostMapping("/addFarmer")
    public AjaxResult addFarmer(@RequestBody Farmer farmer) {
        log.info("新增花农信息，参数：{}", farmer);
        try {
            // 验证用户名是否已存在
            if (farmerService.isUsernameExists(farmer.getUsername())) {
                return AjaxResult.error("用户名已存在");
            }
            
            // 加密密码
            String password = farmer.getPassword();
            farmer.setPassword(Md5Util.getMD5String(password));
            
            // 保存花农信息
            farmerService.addFarmer(farmer);
            return AjaxResult.success("新增成功");
        } catch (Exception e) {
            log.error("新增花农失败", e);
            return AjaxResult.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改花农信息
     * @param farmer
     * @return
     */
    @Log(name = "修改花农信息")
    @PutMapping("/updateFarmer")
    public AjaxResult updateFarmer(@RequestBody Farmer farmer) {
        log.info("修改花农信息，参数：{}", farmer);
        try {
            // 验证用户名是否已存在（排除当前用户）
            if (farmerService.isUsernameExists(farmer.getUsername(), farmer.getFarmerId())) {
                return AjaxResult.error("用户名已存在");
            }
            
            // 如果密码被修改，需要重新加密
            if (farmer.getPassword() != null && !farmer.getPassword().isEmpty()) {
                farmer.setPassword(Md5Util.getMD5String(farmer.getPassword()));
            }
            
            // 更新花农信息
            farmerService.updateFarmer(farmer);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            log.error("修改花农失败", e);
            return AjaxResult.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除花农信息
     * @param id
     * @return
     */
    @Log(name = "删除花农信息")
    @DeleteMapping("/deleteFarmer/{id}")
    public AjaxResult deleteFarmer(@PathVariable Integer id) {
        log.info("删除花农信息，参数：id={}", id);
        try {
            farmerService.deleteFarmer(id);
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("删除花农失败", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取花农信息
     * @param id
     * @return
     */
    @GetMapping("/getFarmerById/{id}")
    public AjaxResult getFarmerById(@PathVariable Integer id) {
        log.info("根据ID获取花农信息，参数：id={}", id);
        try {
            Farmer farmer = farmerService.getFarmerById(id);
            return AjaxResult.success("查询成功", farmer);
        } catch (Exception e) {
            log.error("获取花农信息失败", e);
            return AjaxResult.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取购买者列表
     * @param keyword
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @GetMapping("/getBuyerList")
    public AjaxResult getBuyerList(@RequestParam(required = false) String keyword,
                                  @RequestParam(defaultValue = "1") Integer pageNumber,
                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询购买者列表，参数：keyword={}, pageNumber={}, pageSize={}", keyword, pageNumber, pageSize);
        PageBuyerDto pageBuyerDto = new PageBuyerDto();
        pageBuyerDto.setPageNumber(pageNumber);
        pageBuyerDto.setPageSize(pageSize);
        pageBuyerDto.setKeyword(keyword);
        return AjaxResult.success("查询成功", buyerService.pageListWithShopInfo(pageBuyerDto));
    }

    /**
     * 新增购买者信息
     * @param buyer
     * @return
     */
    @Log(name = "新增购买者信息")
    @PostMapping("/addBuyer")
    public AjaxResult addBuyer(@RequestBody Buyer buyer) {
        log.info("新增购买者信息，参数：{}", buyer);
        try {
            // 验证用户名是否已存在
            if (buyerService.isUsernameExists(buyer.getUsername())) {
                return AjaxResult.error("用户名已存在");
            }
            
            // 加密密码
            String password = buyer.getPassword();
            buyer.setPassword(Md5Util.getMD5String(password));
            
            // 保存购买者信息
            buyerService.addBuyer(buyer);
            return AjaxResult.success("新增成功");
        } catch (Exception e) {
            log.error("新增购买者失败", e);
            return AjaxResult.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改购买者信息
     * @param buyer
     * @return
     */
    @Log(name = "修改购买者信息")
    @PutMapping("/updateBuyer")
    public AjaxResult updateBuyer(@RequestBody Buyer buyer) {
        log.info("修改购买者信息，参数：{}", buyer);
        try {
            // 验证用户名是否已存在（排除当前用户）
            if (buyerService.isUsernameExists(buyer.getUsername(), buyer.getBuyerId())) {
                return AjaxResult.error("用户名已存在");
            }
            
            // 如果密码被修改，需要重新加密
            if (buyer.getPassword() != null && !buyer.getPassword().isEmpty()) {
                buyer.setPassword(Md5Util.getMD5String(buyer.getPassword()));
            }
            
            // 更新购买者信息
            buyerService.updateBuyer(buyer);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            log.error("修改购买者失败", e);
            return AjaxResult.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除购买者信息
     * @param id
     * @return
     */
    @Log(name = "删除购买者信息")
    @DeleteMapping("/deleteBuyer/{id}")
    public AjaxResult deleteBuyer(@PathVariable Integer id) {
        log.info("删除购买者信息，参数：id={}", id);
        try {
            buyerService.deleteBuyer(id);
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("删除购买者失败", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取购买者信息
     * @param id
     * @return
     */
    @GetMapping("/getBuyerById/{id}")
    public AjaxResult getBuyerById(@PathVariable Integer id) {
        log.info("根据ID获取购买者信息，参数：id={}", id);
        try {
            Buyer buyer = buyerService.getBuyerById(id);
            return AjaxResult.success("查询成功", buyer);
        } catch (Exception e) {
            log.error("获取购买者信息失败", e);
            return AjaxResult.error("获取失败：" + e.getMessage());
        }
    }
}
